<?php

namespace app\controller\admin\lineup;

use app\model\admin\basic\BasicGuide;
use app\model\admin\basic\BasicGuideLabel;
use app\model\admin\lineup\LineupGame;
use app\model\admin\lineup\LineupGuideUrl;
use app\model\admin\lineup\LineupStyle;
use app\model\admin\lineup\LineupStyleLabelRelation;
use laytp\controller\Backend;
use laytp\library\CommonFun;

/**
 * Class Career
 * @package app\controller\admin\ah
 */
class Guide extends Backend
{
    protected $model;
    protected $noNeedAuth = ['index', 'info','content'];
    protected $type = 1;

    public function initialize()
    {
        $this->model = new BasicGuide();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 列表
     *  all_data参数的值为true时，表示查询表中所有数据集，否则进行分页查询
     * @return mixed
     */
    public function index()
    {
        $where = $this->buildSearchParams();
        $order = $this->buildOrder();
        $allData = $this->request->param('all_data');
        $searchParam = $this->request->param("search_param");
        $jumpStyle = (new LineupGame())->where("id",$searchParam['lineup_game_id']['value'])->value("jump_style");
        if($jumpStyle==2){
            return $this->success('数据获取成功', []);
        }
        //查询游戏工具下面的对应标签
        $gameStyle = (new LineupStyle())
            ->where('lineup_game_id', $searchParam['lineup_game_id']['value'])
            ->where("status", 1)
            ->find();

        if (!$gameStyle) {
            return $this->success("数据获取成功", []);
        } else {
            $gameStyle = $gameStyle->toArray();
            $labelIds = (new LineupStyleLabelRelation())->where('lineup_style_id', $gameStyle['id'])->where("type", 1)->column("label_id");
            $guide_ids = (new BasicGuideLabel())->whereIn('label_id', $labelIds)->column('guide_id');
            $where[] = [
                'lt_basic_guide.id', 'in', $guide_ids
            ];
        }
        if (isset($searchParam['status']) && !empty($searchParam['status']['value'])) {
            $guides = (new LineupGuideUrl())->whereIn('guide_id',$guide_ids)->where('lineup_game_id',$searchParam['lineup_game_id']['value'])->where("status",1)->column("guide_id");
            if($searchParam['status']['value']==1){
                $where[] = [
                    'lt_basic_guide.id', 'in', $guides
                ];
            }else{
                $where[] = [
                    'lt_basic_guide.id', 'not in', $guides
                ];
            }
        }
        if ($allData) {
            $data = $this->model->where($where)->order($order)->cache(true)->select()->toArray();
        } else {
            $limit = $this->request->param('limit', 10);
            $data = $this->model->with(["url"])->where($where)->order($order)->paginate($limit)->toArray();
            $ids = array_column($data['data'], "id");
            $relationIds = (new LineupGuideUrl())->whereIn("guide_id", $ids)->where('lineup_game_id', $searchParam['lineup_game_id']['value'])->select()->toArray();
            $newData = [];
            foreach ($relationIds as $item) {
                $newData[$item['lineup_game_id'] . "-" . $item['guide_id']] = $item;
            }
            foreach ($data['data'] as $key => $item) {
                $data['data'][$key]['id'] = $searchParam['lineup_game_id']['value'] . "-" . $item['id'];
                if (!isset($newData[$data['data'][$key]['id']])) {
                    $data['data'][$key]['status'] = 2;
                } else {
                    $data['data'][$key]['status'] = $newData[$data['data'][$key]['id']]['status'];
                    $data['data'][$key]['jump_url'] = $newData[$data['data'][$key]['id']]['jump_url'];
                }
            }
        }
        return $this->success('数据获取成功', $data);
    }

    /**
     * 列表
     *  all_data参数的值为true时，表示查询表中所有数据集，否则进行分页查询
     * @return mixed
     */
    public function content()
    {
        $post = $this->request->post();
        //查询游戏工具下面的对应标签
        $guide_ids = (new BasicGuideLabel())->whereIn('label_id', $post['label_ids'])->column('guide_id');
        $where[] = [
            'lt_basic_guide.id', 'in', $guide_ids
        ];
        $data = $this->model->where($where)->order("sort desc")->select()->toArray();
        return $this->success('数据获取成功', $data);
    }

    //设置状态
    public function setStatus()
    {
        $id = $this->request->post('id');
        if(is_array($id)){
            $fieldVal = $this->request->post('field_val');
            $model = new LineupGuideUrl();
            $updateIds = [];
            $insertData = [];
            $lineup_game_id = "";
            foreach ($id as $item){
                $ids = explode("-", $item);
                $lineup_game_id = $ids[0];
                $guide_id = $ids[1];
                $relation = $model->where("lineup_game_id", $lineup_game_id)->where("guide_id", $guide_id)->find();
                if($relation){
                    $updateIds[]= $guide_id;
                }else{
                    $insertData[] = [
                      'lineup_game_id'=>$lineup_game_id,
                      'status'=>$fieldVal,
                      'guide_id'=>$guide_id,
                    ];
                }
            }
            if(count($updateIds)>0){
                $model->where("lineup_game_id", $lineup_game_id)->whereIn("guide_id", $updateIds)->update([
                    'status'=>$fieldVal
                ]);
            }
            if(count($insertData)>0){
                $model->insertAll($insertData);
            }
            return $this->success('操作成功');
        }
        $fieldVal = $this->request->post('field_val');
        $isRecycle = $this->request->post('is_recycle');
        $update['status'] = $fieldVal;
        $ids = explode("-", $id);
        if (count($ids) < 1) {
            return $this->error('数据结构异常，操作失败');
        }
        $model = new LineupGuideUrl();
        $lineup_game_id = $ids[0];
        $guide_id = $ids[1];
        $relation = $model->where("lineup_game_id", $lineup_game_id)->where("guide_id", $guide_id)->find();
        if ($relation) {
            try {
                if ($isRecycle) {
                    $updateRes = $model->onlyTrashed()->where('id', '=', $relation->id)->update($update);
                } else {
                    $updateRes = $model->where('id', '=', $relation->id)->update($update);
                }
                if ($updateRes) {
                    return $this->success('操作成功');
                } else if ($updateRes === 0) {
                    return $this->success('未作修改');
                } else {
                    return $this->error('操作失败');
                }
            } catch (\Exception $e) {
                return $this->error('数据库异常，操作失败');
            }
        } else {
            $update['lineup_game_id'] = $lineup_game_id;
            $update['guide_id'] = $guide_id;
            $res = $model->insert($update);
            if ($res) {
                return $this->success('操作成功');
            } else if ($res === 0) {
                return $this->success('未作修改');
            } else {
                return $this->error('操作失败');
            }
        }

    }


    //编辑
    public function edit()
    {
        $id = $this->request->param('id');
        $ids = explode("-", $id);
        if (count($ids) < 1) {
            return $this->error('数据结构异常，操作失败');
        }
        $model = new LineupGuideUrl();
        $lineup_game_id = $ids[0];
        $guide_id = $ids[1];
        $info = $model->where('guide_id', $guide_id)->where('lineup_game_id', $lineup_game_id)->find();
        $post = CommonFun::filterPostData($this->request->post());
        //不存在做新增
        if (!$info) {
            $data = [
                'guide_id' => $guide_id,
                'lineup_game_id' => $lineup_game_id,
                'jump_url' => $post['jump_url'],
            ];
            $res = $model->insert($data);
            if ($res) {
                $this->clearCache();
                return $this->success('编辑成功');
            } else {
                return $this->error('编辑失败');
            }
        }
        if (isset($post->icon) && !empty($post->icon)) {
            $post->icon = getRelativeUrl($post->icon);
        }
        unset($post['id']);
        foreach ($post as $k => $v) {
            $info->$k = $v;
        }
        try {
            $updateRes = $info->save();
            if ($updateRes) {
                $this->clearCache();
                return $this->success('编辑成功');
            } else {
                return $this->error('编辑失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    public function info()
    {
        $id = $this->request->param('id');
        $ids = explode("-", $id);
        if (count($ids) < 1) {
            return $this->error('数据结构异常，操作失败');
        }
        $model = new LineupGuideUrl();
        $lineup_game_id = $ids[0];
        $guide_id = $ids[1];
        $info = $model->where('guide_id', $guide_id)->where('lineup_game_id', $lineup_game_id)->find();
        if (!$info) {
            $info = [
                'jump_url' => ''
            ];
        }
        $guide = (new BasicGuide())->where("id", $guide_id)->find();
        if ($guide) {
            $info['name'] = $guide->name;
            $info['icon'] = $guide->icon;
        }
        $info['id'] = $id;
        return $this->success('获取成功', $info);
    }
}